package com.jialiang.blossom.uitl;

import com.iceyyy.nongli.NongLi;
import com.jialiang.blossom.model.Time;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;

/**
 * 获取当前农历时间
 */
public class GetNongLiTime extends NongLi {

    /**
     * 获取当前农历时间
     *
     * @return
     */
    public static Time getNongLiIng() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        // 根据当前日期获取农历日期
        int[] ints = new int[]{year, month, day};
        int[] date = getDate(ints);
        year = date[0];
        month = date[1];
        day = date[2];

        return new Time(year, month, day, hour, minute);
    }

    public static int[] getDate(int[] dateArray) {
        try {
            int year = dateArray[0];
            for (int i = 1; i < 2; i++) {
                if (("" + dateArray[i]).length() < 2) {
                    dateArray[i] = Integer.parseInt("0" + dateArray[i]);
                }
            }
            if (year < 1700 || year > 3161) {
                throw new RuntimeException("-输入的日期年份超出范围");
            } else {
                String dateStr = cast(dateArray);
                int[] i = cast2Array(dateStr);
                return i;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String cast(int[] dateArray) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method cast = NongLi.class.getDeclaredMethod("cast", int[].class);
        cast.setAccessible(true);
        return (String) cast.invoke(null, dateArray);
    }

    private static int[] cast2Array(String dateStr) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method cast2Array = NongLi.class.getDeclaredMethod("cast2Array", String.class);
        cast2Array.setAccessible(true);
        return (int[]) cast2Array.invoke(null, dateStr);
    }

}
